package com.whut.mobilesafe.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.whut.mobilesafe.R;
import com.whut.mobilesafe.db.dao.AntiVirtusDao;
import com.whut.mobilesafe.domain.AppInfo;
import com.whut.mobilesafe.domain.ScanInfo;
import com.whut.mobilesafe.engine.AppInfoProvider;
import com.whut.mobilesafe.utils.MD5Utils;

import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 作    者：yubo.xiaoyubo
 * 时    间：2016/1/1  10:35.
 * 版    本：1.0
 * 描    述：
 * 1.获取程序中已经安装的所有应用
 * 2.拿应用名去数据库中查询是否存在,存在就红色显示。不存在就黑色显示
 * 3.把扫描的应用名称加入到container中
 */
public class AntiVirtusActivity extends Activity {

    private static final int STATE_UPDATE_SCAN = 1;//更新状态
    public static final int STATE_UPDATE_FINISH = 2;//更新完毕

    private ArrayList<AppInfo> mAllAppInfoList;
    private FrameLayout frameLayout;
    private TextView tvTitle;
    private ProgressBar pbLoading;
    private LinearLayout llContainer;
    private ImageView ivScan;
    private ArrayList<ScanInfo> mVirtusList = new ArrayList<>();
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            ScanInfo scanInfo = (ScanInfo) msg.obj;

            switch (msg.what) {
                case STATE_UPDATE_SCAN:
                    TextView textView = new TextView(getApplicationContext());

                    if (scanInfo.isVirtus) {
                        textView.setText("发现病毒: " + scanInfo.name);
                        textView.setTextColor(Color.RED);
                        Log.d("AntiVirtusActivity", "+++++++++");
                        mVirtusList.add(scanInfo);
                        Log.d("AntiVirtusActivity", "+++++++++");
                        Log.d("AntiVirtusActivity", "mVirtusList.size():--" + mVirtusList.size());
                    } else {
                        textView.setText("扫描安全：" + scanInfo.name);
                        textView.setTextColor(Color.BLACK);
                    }

                    llContainer.addView(textView, 0);

                    tvTitle.setText("正在扫描:" + scanInfo.name);
                    break;

                case STATE_UPDATE_FINISH:

                    tvTitle.setText("扫描完毕");
                    ivScan.clearAnimation();
                    Log.d("AntiVirtusActivity", "mVirtusList.size():" + mVirtusList.size());
                    if (!mVirtusList.isEmpty()) {
                        //Toast.makeText(AntiVirtusActivity.this, "您的手机发现了" + mVirtusList.size() + "个病毒", Toast.LENGTH_SHORT).show();
                        showAlertDialog();
                    } else {
                        Toast.makeText(AntiVirtusActivity.this, "您的手机很安全,请放心使用!", Toast.LENGTH_SHORT).show();
                    }
                    break;

            }

        }
    };


    //显示警告对话框
    private void showAlertDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("严重警告");
        builder.setMessage("发现病毒 "+mVirtusList.size() + " 个，请立即处理！！");
        builder.setCancelable(false);
        builder.setNegativeButton("稍后处理",null);
        builder.setPositiveButton("立即处理", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                for(ScanInfo info:mVirtusList){
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_DELETE);
                    intent.setData(Uri.parse("package:" + info.name));
                    startActivity(intent);
                }
            }
        });

        builder.show();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_anti_virtus);

        frameLayout = (FrameLayout) findViewById(R.id.frameLayout);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        pbLoading = (ProgressBar) findViewById(R.id.pb_loading);
        llContainer = (LinearLayout) findViewById(R.id.ll_container);
        ivScan = (ImageView) findViewById(R.id.iv_scan);

        RotateAnimation ra = new RotateAnimation(0, 360,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                0.5f);
        ra.setDuration(2000);
        ra.setRepeatCount(Animation.INFINITE);
        ivScan.startAnimation(ra);

        initData();
    }

    //获取所有的在手机上已经安装的应用
    private void initData() {
        new Thread() {


            @Override
            public void run() {
                PackageManager pm = getPackageManager();
                // 获取已安装app, 某些app卸载之后,还残留data/data目录数据,也要加载出来
                List<PackageInfo> installedPackages = pm
                        .getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);

                pbLoading.setMax(installedPackages.size());

                int progress = 0;
                for (PackageInfo info : installedPackages) {
                    ScanInfo scanInfo = new ScanInfo();
                    //查询是不是病毒
                    String apkPath = info.applicationInfo.sourceDir;// 获取应用apk文件的地址
                    String md5 = MD5Utils.encodeFile(apkPath);
                    boolean isVirtus = AntiVirtusDao.querybyApkSourceDir(getApplicationContext(), md5);

                    scanInfo.isVirtus = isVirtus;
                    scanInfo.name = info.applicationInfo.loadLabel(pm).toString();
                    scanInfo.icon = info.applicationInfo.loadIcon(pm);

                    Message msg = Message.obtain();
                    msg.obj = scanInfo;
                    msg.what = STATE_UPDATE_SCAN;
                    mHandler.sendMessage(msg);

                    progress++;
                    pbLoading.setProgress(progress);

                    SystemClock.sleep(100 + new Random().nextInt(100));
                }
                Message msg = Message.obtain();
                msg.what = STATE_UPDATE_FINISH;
                mHandler.sendMessage(msg);
            }
        }.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
